package com.lihepeng.leecode.integer;


import org.junit.Test;

/**
 * 判断一个整数是不是回文数
 *
 * @author eloancn
 */
public class Solution_09 {
    public boolean isPalindrome_01(int x) {
        if (x < 0) {
            return false;
        }
        int revertInt = revertInt(x);
        if (revertInt == 0) {
            return false;
        }
        if (revertInt == x) {
            return true;

        }
        return false;
    }

    // 反转数字的一半，如果和另外一半相同，则是回文
    public boolean isPalindrome(int x) {
        if (x < 0 || (x % 10 == 0 && x != 0)) {
            return false;
        }
        // 遍历
        int revertNum = 0;
        while (x > revertNum) {
            revertNum = revertNum * 10 + x % 10;
            x /= 10;
        }
        return x == revertNum || x == revertNum / 10;
    }

    @Test
    public void runTest() {
        boolean palindrome = isPalindrome(101);
        System.out.println(palindrome);
    }

    // 反转整数
    public int revertInt(int x) {
        int rev = 0;
        while (x != 0) {
            int pop = x % 10;
            x /= 10;
            if (rev > Integer.MAX_VALUE / 10 || rev == Integer.MAX_VALUE / 10 && pop > 7) {
                return 0;
            }
            if (rev < Integer.MIN_VALUE / 10 || rev == Integer.MIN_VALUE / 10 && pop < -8) {
                return 0;
            }
            rev = rev * 10 + pop;
        }
        return rev;
    }
}
